package com.hs.telepass.controller;


import android.content.Intent;
import com.hs.telepass.controller.task.Task;
import com.hs.telepass.model.json.response.UpdatePasswordResponseJson;
import com.hs.telepass.model.json.response.VerifyPasswordResponseJson;
import com.hs.telepass.utils.JsonUtil;
import com.hs.telepass.utils.LogUtil;
import com.hs.telepass.utils.security.AESEnc;
import com.hs.telepass.utils.security.Base64Utils;

public class VerifyPasswordTask extends Task{
    public final static String ACTION_VERIFY_PASSWORD_TASK = "action_verify_password_task";

    private String jsonRequstStr;
    private String taskUrl;
    private int requestType;
    private String runtime_key;

    public VerifyPasswordTask(String sid, String req, String runtime_key){
        jsonRequstStr = "sid=" + sid + "&" + "req=" + req;
        requestType = TASK_REQUST_TYPE_POST;
        taskUrl = BASE_API_URL + "/app/" + "verify";
        this.runtime_key = runtime_key;
    }

    @Override
    public void onExecuted(String response, int httpCode) {
        Intent intent = new Intent(getActionName());
        VerifyPasswordResponseJson json = JsonUtil.fromJson(response, VerifyPasswordResponseJson.class);
        String code = json.getCode();
        if("200".equals(code)){
            String valid = json.getValid();
            AESEnc aesEnc = new AESEnc(runtime_key.getBytes());
            String result;
            try {
                byte byteResult[] = aesEnc.decrypt(Base64Utils.decode(valid));
                result = new String(byteResult);
                LogUtil.i( "verifyPsw result : " + result);
                if("true".equals(result)){
                    intent.putExtra(TaskController.EXTRA_EVENT, TaskController.EVENT_TASK_SUCCEED);
                }else {
                    intent.putExtra(TaskController.EXTRA_EVENT, TaskController.EVENT_TASK_ERROR);

                }


            } catch (Exception e) {
                e.printStackTrace();
                intent.putExtra(TaskController.EXTRA_EVENT, TaskController.EVENT_TASK_ERROR);
            }
        }else {
            intent.putExtra(TaskController.EXTRA_EVENT, TaskController.EVENT_TASK_ERROR);
        }
        broadcastManager.sendBroadcast(intent);
    }

    @Override
    public int getRequstType() {
        return requestType;
    }

    @Override
    public String getJsonRequstStr() {
        return jsonRequstStr;
    }

    @Override
    public int getResponseSuccessCode() {
        return 0;
    }

    @Override
    public String getTaskUrl() {
        return taskUrl;
    }

    @Override
    public String getActionName() {
        return ACTION_VERIFY_PASSWORD_TASK;
    }
}
